import {base, high} from 'nc-lightapp-front';
import React from 'react';

const {Refer} = high;
const PopRefer = Refer.PopRefer;
const {NCButton: Button, NCCheckbox: Checkbox, NCCollapse: Collapse, NCTable: Table} = base;
const MultiLangWrapper = Refer.MultiLangWrapper;

class MyRefer extends PopRefer {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.setState({
            includeChildren: true
        })
    }

    // 多选的方法
    multiSelect = () => {
        document.body.style.overflow = this.prevOverFlow;
        delete this.prevOverFlow;
        let selections = this.getSelections(),
            {onChange, extraOnChange} = this.props;

        let isEqual = this.isEqual(selections.map(e => e.refpk), [...this._value.keys()]);

        isEqual || this.pushToLocal([...selections]);

        let index = selections.length > 1 ? selections.findIndex(e => /^#.*#$/.test(e.refpk)) : -1;

        if (index !== -1) {
            selections.splice(index, 1);
        }

        this.setState(
            {
                referVal: '',
                isMoreButtonShow: false
            },
            () => {
                let foolDisplay = this.getDisplayOrValue(selections, 'display'),
                    foolValue = this.getDisplayOrValue(selections, 'value');
                /*this.runFunction([!isEqual && onChange, !isEqual && extraOnChange], selections, {
                    display: foolDisplay,
                    value: foolValue
                }, this.myHandlePopoverBlur());*/
                if (this.clearFlag) {
                    this.clearFlag = false;
                }
                onChange && onChange(selections, {
                    display: foolDisplay,
                    value: foolValue
                }, this.cancel);
            }
        );
    };

    // 树的双击事件
    onTreeNodeDoubleClick = (checkedKeys, {node}) => {
        let {refType, isMultiSelectedEnabled, pageSize, idKey} = this.props,
            pid = node.props.treeNodeData[idKey],
            {searchVal, isExpandLeftArea, expandedKeys} = this.state;
        if (refType === 'tree') {
            let {selectedValues} = this.treeSelect(node, true);
            this.setState(
                {
                    selectedValues
                },
                () => {
                    if (!node.props.disableCheckbox && !isMultiSelectedEnabled) {
                        isMultiSelectedEnabled
                            ? this.multiSelect()
                            : this.singleSelect([...selectedValues.values()][0]);
                        this.handlePopoverBlur();
                    }
                }
            );
        } else if (refType === 'gridTree' && isExpandLeftArea) {
            // 树表时，并且左侧树展开时：选中节点，收起展开
            this.loadAndSetTableData({
                pid: node.props.treeNodeData.refpk,
                pageInfo: {
                    pageIndex: 0,
                    pageSize
                },
                keyword: searchVal
            });
            this.setState({
                isExpandLeftArea: false,
                expandedKeys: [...new Set([...expandedKeys, pid])]
            });
        }
        this.setState({
            selectedKeys: [pid]
        });
        let keyPressFlag = false;
        if (window.event && ['keyCode', 'charCode', 'which'].find(e => window.event[e])) {
            keyPressFlag = true;
        }
        if (keyPressFlag && refType === 'tree') {
            this.onHotKeyClose();
        }
    };

    // 复写原型方法：渲染弹出层底部
    renderPopoverBottom = () => {
        let {selectedShow, isShow} = this.state,
            selectColumns = [];
        const {isMultiSelectedEnabled, refType, isRunWithChildren, rowKey} = this.props;
        selectColumns.push({
            // 操作
            title: this.state.jsonInsideRefer['containers-refer-0025'],
            key: 'operate',
            width: 100,
            fixed: 'right',
            render: (text, row, index) => {
                return (
                    <span className="refer-del" onClick={this.onSelectedRowClick.bind(null, row, index)}>
						{/* 移除 */}
                        {this.state.jsonInsideRefer['containers-refer-0026']}
					</span>
                );
            }
        });
        let height = isShow ? ((this.popover || {}).clientHeight || 0) - 85 : 0; // header + footer = 85
        selectColumns.unshift(...this.getCommonColumns());
        return [
            isMultiSelectedEnabled && (
                <div className="refer-selected" key="1">
                    <Button
                        onClick={() => {
                            this.setState({
                                selectedShow: !selectedShow
                            });
                        }}
                    >
                        {/* 已选 */}
                        {`${this.state.jsonInsideRefer['containers-refer-0027']}:（${this.getSelections().length}）`}
                    </Button>
                    <Collapse in={selectedShow} className="refer-collapse">
                        <div>
                            <div className="refer-collapse-header">
                                <div className="refer-title" key="1">
                                    {/* 查看已选 */}
                                    {this.state.jsonInsideRefer['containers-refer-0028']}
                                </div>
                                <div className="refer-close" key="3">
									<span
                                        onClick={() => {
                                            this.setState({
                                                selectedValues: new Map()
                                            });
                                        }}
                                    >
										{/* 清空 */}
                                        {this.state.jsonInsideRefer['containers-refer-0029']}
									</span>
                                    <span
                                        style={{color: '#555'}}
                                        onClick={() => {
                                            this.setState({
                                                selectedShow: false
                                            });
                                        }}
                                    >
										{/* 收起 */}
                                        {this.state.jsonInsideRefer['containers-refer-0030']}
									</span>
                                </div>
                            </div>
                            <div
                                className="refer-table"
                                style={{height, padding: '15px 20px 0', boxSizing: 'border-box'}}
                            >
                                <Table
                                    // lazyload={false}
                                    height={35}
                                    headerHeight={35}
                                    rowKey={rowKey}
                                    scroll={{x: true, y: height - 50}} // 表头 + padding-top = 50
                                    columns={selectColumns}
                                    data={this.getSelections()}
                                    emptyText={() => this.state.jsonInsideRefer['containers-refer-0024']}
                                />
                            </div>
                        </div>
                    </Collapse>
                </div>
            ),
            // 树形参照是否执行时包含下级
            // isMultiSelectedEnabled &&
            refType === 'tree' &&
            // !onlyLeafCanSelect &&
            isRunWithChildren && (
                <Checkbox
                    className="include-children"
                    checked={this.state.runWithChildren}
                    onClick={() => {
                        this.setState({
                            runWithChildren: !this.state.runWithChildren
                        });
                    }}
                    tabIndex={this.getTabIndex(this.hotKeyElement.runWithChildren)}
                >
                    {/* 执行时包含下级 */}
                    {this.state.jsonInsideRefer['containers-refer-0031']}
                </Checkbox>
            ),
            <div className="refer-bottom-extend" key="2">
                {this.renderPopoverBottomExtend()}
            </div>,
            <div className="buttons" key="3">
                <Button
                    onClick={() => {
                        isMultiSelectedEnabled ? this.multiSelect() : this.singleSelect(this.getSelections()[0]);
                    }}
                    className="sure-btn"
                >
                    {/* 确定 */}
                    {this.state.jsonInsideRefer['containers-refer-0032']}
                </Button>
                <Button onClick={this.cancel} className="cancel-btn">
                    {/* 取消 */}
                    {this.state.jsonInsideRefer['containers-refer-0033']}
                </Button>
            </div>
        ];
    };
}

MyRefer = MultiLangWrapper(MyRefer);
export default MyRefer